(function() {
  var name_label_display = 'Name:';
  this.tags_dropdown_incrementor = 1;
  this.all_tags = [];
  this.removed_tags = [];
  this.task_priority_dropdown = [];
  this.count = 1;
  this.recreate_tag_dropdowns = true;
  this.recreate_filter_tag_dropdowns = true;
  this.filter_val = '';
  const max_name_length = 255;  
  const max_note_length = 1024;  
  
  $.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) {
      window.showMessage("Error", false, false, XMLHttpRequest.responseText);
  }});
  
  $(window).load(function(event) { 
    $('#filter_tasks_completion_dropdown').val(3);
    $('#filter_tasks_data_span').val(1);
    $('#filter_tasks_dropdown').val('');
    $('#filter_tasks_sort_field').val('');
    $('#filter_tasks_sort_direction').val('');
    $('#lookup_select').val('');
    setVals();
    createTagsDropdown(tags_dropdown_incrementor);
    createPriorityDropdown();
    setTimeout('hideAddressBar();', 2000);
    $('#page_title').show();
    showButtons(['search']);
    loadHomeShortcuts();
    $('#home_shortcut_tag_checkbox').attr('checked', false);
  });
  
  $(window).keypress(function(event) {
    if(event.target.id == 'name')
    {
     if($("#name_label").html() == name_label_display)
     {
       clear_name_label();
     }
    }
    if(event.keyCode == 13 || event.keyCode == 10) 
    {
      if(event.target.id === 'search') {
        $.ajax({
          url:"ajax.php?action=listTasks&filter=search&value=" + $('#search').val(),
          success: function(lines)
          {
            if(lines != 'error')
            {
              $("#task_list").html(lines);
              showButtons(['filter']);  
              showPage(document.getElementById('task_list'));       
            }
            else
            {
              showMessage('Error listing lines', false);
            }
          }
        });
      } 
      if(event.target.id == 'be_input')
      {
        addBe();
      }
      else
      {
        if(event.target.className.indexOf('task_page') != -1)
        {
          saveTask();
        }
        if(event.target.className.indexOf('add_tag') != -1)
        {
          addTag();
        }
        else
        {
          switch(event.target.className)
          {
            case 'filter_select':
              filterSubmit();
              break;
          }
        }
      }
    }
    if (event.which == 115 && event.ctrlKey) {
      saveTask();
      event.preventDefault();        
    }
  });
                               
  $(window).change(function(event) { // addEventListener("change", function(event)
    if(event.target.id == 'lookup_select'){
     window.location=$('#lookup_select').val() + $('#name').val();
    }
    if(event.target.id == 'super_tags_dropdown_selector')
    {
     addSuperTag(event.target.value);
    }
    if(event.target.id == 'sub_tags_dropdown_selector')
    {
     addSubTag(event.target.value);
    }
    if(event.target.className.indexOf("tags_dropdown") != -1)
    {
      if(event.target.value == 'new')
      {
        id=event.target.id;
        $("#" + id).hide();
        $("#tags").show();
        $('#tags_input').focus();
        createTagsDropdown(tags_dropdown_incrementor);    
      }
      else
      {
        createTagsDropdown(tags_dropdown_incrementor);
      }
    }
  });
  
  $(window).click(function(event) { //addEventListener("click", function(event) {
    hideAddressBar();
    switch(event.target.id)
    {
      case 'search':
        $('#search').css('opacity', .99).val('');
        break;
      case 'filter_submit': 
        filterSubmit();
        break;                     
      case 'home_button':
        showButtons(['search']);
        reset();
        break;
      case 'action_button':
        add_task();
        break;
      case 'home_shortcut_tag_checkbox':
        toggleHomeShortcut($('#tag_name').attr('name'));
        break;
      case 'home_tags':
        listTags();
        break;
      case 'name':
        clear_name_label();
        break;
      case 'save_task':
        saveTask();
        break;
      case 'remove':
        remove();
        break;
      case 'completed':
        completed();
        break;
      case 'not_completed':
        notCompleted();
        break;
      case 'activate':
        activate();
        break;
      case 'deactivate':
        deactivate();
        break;
      case 'answer':
        showAnswer();
        break;
      case 'previous':
        showPreviousQuestion();
        break;
      case 'next':
        showNextQuestion();
        break;
      case 'home_counters':
        populateCounters();
        break;
      case 'home_bs':
        populateBS();
        showButtons(['add_bs_item']);
        break;
      case 'home_be':
        populateBe();
        break;
      case 'reset_counters':
        resetAllCounters();
        break;
      case 'add_bs_item':
        addBSItem();
        break;
      case 'add_counter_item':
        addCounter();
        break;
      case 'add_tag':
        addTag2();
        break;
      case 'home_qna':
        listQnaTags();
        break;
      case 'filter':
        createFilterTagsDropdown();
        setTimeout('$("#filter_tasks_dropdown").focus();', 400);
        showButtons(['filter_submit']);
        showPage(document.getElementById('Filter'));
        break;
      case 'list':
        listTasks(filter_val);
        showPage(document.getElementById('task_list'));
        break;
      case 'delete_tag':
        deleteTag($('#tag_name').attr('name'))
        break;
      case 'list_tags':
        listTags();
        break;
      case 'list_tasks':
        listTasks($('#tag_name').attr('name'), 3, 1);
        showPage(document.getElementById('task_list'));
        break;
      case 'add_tag':
        addTag2();
        break;
      case 'edit_tag_button':
        populateTag($("#filter_tasks_dropdown :selected").text(), $("#filter_tasks_dropdown").val());
        showPage(document.getElementById('edit_tag'));
        break;
      default:
    }
    if(event.target.className.indexOf('message_details_link') != '-1')
    {
      $('.message_details').toggle();
    }  
    if(event.target.className.indexOf('home_') != '-1')
    {
      listTasks(event.target.id.replace('home_', ''), 3, 1);
    }  
    if(event.target.className.indexOf('qna_tag') != '-1')
    {
      displayQna(event.target.id.replace('qna_tag_id_', ''));
    }  
    if(event.target.className.indexOf('line') != '-1')
    {
      displayTask(event);
    }
    if(event.target.className.indexOf('remove_supertag') != '-1')
    {
      removeSupertag(event.target.id.replace('remove_supertag_',''));
    }
    if(event.target.className.indexOf('remove_subtag') != '-1')
    {
      removeSubtag(event.target.id.replace('remove_subtag_',''));
    }
    if(event.target.className.indexOf('incrementor') != '-1')
    {
      $.ajax({
        url:"ajax.php?action=increment&counter_id=" + event.target.id.replace('increment_counter_',''),
        success: function(val)
        {
          populateCounters(); 
        }
      });
    }
    if(event.target.className.indexOf('decrementor') != '-1')
    {
      $.ajax({
        url:"ajax.php?action=decrement&counter_id=" + event.target.id.replace('decrement_counter_',''),
        success: function(val)
        {
          populateCounters(); 
        }
      });
    }
    if(event.target.className == 'remove_counter')
    {
      removeCounterItem(event.target.id.replace('remove_counter_', ''));
    }
    if(event.target.className == 'tag')
    {
      populateTag(event.target.innerHTML, event.target.id.replace('tag_id_',''));
      showPage(document.getElementById("edit_tag"));
    }
  });
  
  add_task = function() 
  {
    reset();
    showButtons(['save_task','list']);
    showPage(document.getElementById('tasks'));
    $('.tags_dropdown').val(filter_val);
    if(filter_val != ''  && filter_val != 'active') createTagsDropdown();
  }
  
  deleteTag = function(id)
  {
    if(confirm("Remove " + $('#tag_name').html() + " tag?"))
    {
      $.ajax({
        url:"ajax.php?action=removeTag&id=" + id,
        success: function(data)
        {
          populateTag($('#tag_name').html(), $('#tag_name').attr('name'));
          showMessage(data, true);
        }
      });
    }
  }
  
  removeSupertag = function(supertag_id)
  {
    if(confirm("Remove '" + $('#super_tag_item_' + supertag_id).attr('name') + "' supertag"))
    {
      $.ajax({
        url:"ajax.php?action=removeSupertag&supertag_id=" + supertag_id,
        success: function()
        {
          populateTag($('#tag_name').html(), $('#tag_name').attr('name')); 
        }
      });
    }
  }
  
  removeSubtag = function(subtag_id)
  {
    if(confirm("Remove '" + $('#sub_tag_item_' + subtag_id).attr('name') + "' subtag"))
    {
      $.ajax({
        url:"ajax.php?action=removeSubtag&subtag_id=" + subtag_id,
        success: function()
        {
          populateTag($('#tag_name').html(), $('#tag_name').attr('name')); 
        }
      });
    }
  }
  
  populateTag = function(tag_name, tag_id)
  {
    $('#tag_name').html(tag_name).attr('name', tag_id);
    eip_tag_name(tag_id);
    populateTagSupertags(tag_id);
    populateTagSubtags(tag_id);
    checkHomeShortcut(tag_id);
    showButtons(['list_tags', 'list_tasks', 'add_tag', 'delete_tag']);
    
    if(typeof($("#super_tags_dropdown_selector").val()) == "undefined")
    {
      $("<select>").attr("id", "super_tags_dropdown_selector"). attr("class", "tags_dropdown tags_page").appendTo("#super_tags_dropdown");
      $("<option>").attr("value", "").text("Select tag").appendTo("#super_tags_dropdown_selector");
      $.ajax({
        url:"ajax.php?action=getAllTags2&tag_id=" + tag_id,
        success: function(data)
        {
          $("#super_tags_dropdown_selector").append(data);
          $('#super_tags_dropdown').show();
          $('#super_tags_dropdown_selector').focus();
        }
      });    
    }
    else {
      $("#super_tags_dropdown_selector").val('');
    }
    
    if(typeof($("#sub_tags_dropdown_selector").val()) == "undefined")
    {
      $("<select>").attr("id", "sub_tags_dropdown_selector"). attr("class", "tags_dropdown tags_page").appendTo("#sub_tags_dropdown");
      $("<option>").attr("value", "").text("Select tag").appendTo("#sub_tags_dropdown_selector");
      $.ajax({
        url:"ajax.php?action=getAllTags2&tag_id=" + tag_id,
        success: function(data)
        {
          $("#sub_tags_dropdown_selector").append(data);
          $('#sub_tags_dropdown').show();
          $('#sub_tags_dropdown_selector').focus();
        }
      });    
    }
    else {
      $("#sub_tags_dropdown_selector").val('');
    }        
  }
  
  checkHomeShortcut = function(tag_id){
    $.ajax({
      url:"ajax.php?action=checkHomeShortcut&tag_id=" + tag_id,
      success: function(checked)
      {
        if(checked == 1){
          $('#home_shortcut_tag_checkbox').attr('checked', true);
        }
        if(checked == 0){
          $('#home_shortcut_tag_checkbox').attr('checked', false);
        }
      }
    });
  }
  
  populateTagSupertags = function(tag_id)
  {
    $.ajax({
      url:"ajax.php?action=populateTagSupertags&tag_id=" + tag_id,
      success: function(data)
      {
        $('#tag_supertags').html(data);
      }
    });
  }    
  
  populateTagSubtags = function(tag_id)
  {
   $.ajax({
      url:"ajax.php?action=populateTagSubtags&tag_id=" + tag_id,
      success: function(data)
      {
        $('#tag_subtags').html(data);
      }
    });
  }    
  
  addTag = function()
  {
    if($('#tags_input').val() === '')
    {
      alert('Please enter a tag value');
    }
    else
    {
      $.ajax({
        url:"ajax.php?action=addTag&tag=" + $('#tags_input').val(),
        success: function(val_index)
        {
          updateTagsDropdown(val_index);
          showMessage($('#tags_input').val() + ' tag successfully added', true);
          $('#tags_input').val('');
        }
      });
    }
  }
  
  addTag2 = function()
  {
    $('#super_tags_dropdown').html('');
    $('#sub_tags_dropdown').html('');
    tag_name = '';
    showButtons(['list_tags', 'list_tasks', 'add_tag', 'delete_tag']);
    $.ajax({
      url:"ajax.php?action=addTag&tag=" + tag_name,
      success: function(tag_id)
      {
        showMessage('tag successfully added', true);
        populateTag(tag_name, tag_id);
        showPage(document.getElementById('edit_tag'));
      }
    });    
  }
  
  createFilterTagsDropdown = function()
  {
    if(recreate_filter_tag_dropdowns)
    {
      $('#filter_tasks_dropdown').html('');
      $("<option>").attr("value", "").text('Select Tag').appendTo("#filter_tasks_dropdown");
      $.each(this.all_tags, function(key, value){
        $("<option>").attr("value", value.id).text(value.name).appendTo("#filter_tasks_dropdown");
      });
      $("<option>").attr("value", "notags").text("No Tags").css('font-style', 'italic').appendTo("#filter_tasks_dropdown");
    }
    recreate_filter_tag_dropdowns = false;
  }
  
  updateTagsDropdown = function(selected_index)
  {
    old_incrementor = tags_dropdown_incrementor - 1;
    $('#tags_dropdown' + old_incrementor).hide();
    recreate_tag_dropdowns = true;
    createTagsDropdown(tags_dropdown_incrementor, selected_index);
  }
  
  showPreviousQuestion = function()
  {
    showQuestion(--this.count);
  }
  
  showNextQuestion = function()
  {
    showQuestion(++this.count);
  }
  
  showQuestion = function()
  {
    $('.qna').hide();
    $('#qna_question_id_'+ this.count).show();
  }
  
  showAnswer = function()
  { 
    $('#qna_answer_id_'+ this.count).show();
  }
  
  displayQna = function(id)
  {
    $.ajax({
      url:"ajax.php?action=displayQna&tag_id=" + id,
      success: function(data)
      {
        $('#qna').html(data);
        showQuestion();
        showButtons(['previous', 'answer', 'next']);
      }
    });
  }
  
  listQnaTags = function()
  {
    $.ajax({
      url:"ajax.php?action=listQnaTags",
      success: function(data)
      {
        $('#qna').html(data); 
      }
    });
  }
  
  filterSubmit = function()
  {
    listTasks();
    showPage(document.getElementById("task_list"));
    showButtons(['filter']);
  }
  
  resetAllCounters = function()
  {
    if(confirm("Reset all counters?"))
    {
      $.ajax({
        url:"ajax.php?action=resetAllCounters",
        success: function(val)
        {
          populateCounters();
        }
      });
    }
  }
  
  removeCounterItem = function(id)
  {
    if(confirm("Remove this item?"))
    {
      $.ajax({
        url:"ajax.php?action=removeCounterItem&id=" + id,
        success: function(val)
        {
          populateCounters();
        }
      });
    }
  }
  
  priorityUpCounterItem = function(id)
  {
    $.ajax({
      url:"ajax.php?action=priorityUpCounterItem&id=" + id,
      success: function(val)
      {
        populateCounters();
      }
    });
  }
  
  priorityDownCounterItem = function(id)
  {
    $.ajax({
      url:"ajax.php?action=priorityDownCounterItem&id=" + id,
      success: function(val)
      {
        populateCounters();
      }
    });
  }
  
  removeBSItem = function(id)
  {
    if(confirm("Remove this item?"))
    {
      $.ajax({
        url:"ajax.php?action=removeBS&id=" + id,
        success: function(val)
        {
          populateBS();
        }
      });
    }
  }
  
  eip_tag_name = function(id){
    $(".tag_name").editInPlace({
      url: "ajax.php?action=eip_tag_name&id=" + id,
      saving_image: "loading.gif",
      default_text: "(empty)",
      show_buttons: 1,
      success:function()
      {
        updateTagsDropdown();
      }
    });
  }
  
  eipBsd = function() {
    $(".bs_description").editInPlace({
      url: "ajax.php?action=eipbsd",
      saving_image: "loading.gif",
      default_text: "(empty)",
      show_buttons: 1
    });
  }
  
  eipBsa = function () {
    $(".bs_amount").editInPlace({
      url: "ajax.php?action=eipbsa",
      saving_image: "loading.gif",
      default_text: "(empty)",
      show_buttons: 1
    });
  }
  
  eipCounters = function () {
    $(".counter_description").editInPlace({
      url: "ajax.php?action=eipCounterDescription",
      saving_image: "loading.gif",
      default_text: "(empty)",
      show_buttons: 1,
      success:function()
      {
        populateCounters();
      }
    });
    $(".counter_value").editInPlace ({
      url: "ajax.php?action=eipCounterValue",
      saving_image: "loading.gif",
      default_text: "(empty)",
      show_buttons: 1,
      success:function()
      {
        populateCounters();
      }
    });
  }
  
  refreshTaskButtons = function (task_id) {
    $.ajax({
      url: "ajax.php?action=getTaskButtonValues&task_id=" + task_id,
      dataType: 'json',
      success: function(data){
          if(data[0].completed == 1) { complete = 'not_completed'; } else { complete = 'completed'; } 
          if(data[0].active == 1) { activated = 'deactivate'; } else { activated = 'activate'; }
          showButtons(['save_task', complete, 'remove', activated , 'list']);
      }
    });
  }
  
  displayTask = function(event)
  {
    $('#reset_all').hide();
    $('.message').hide();
    var line_id = event.target.id.replace('task_','');
    refreshTaskButtons(line_id);
    $("#tags_dropdown").html("");
    $.getJSON("ajax.php?action=getTaskTags&task_id=" + line_id,
      function(data){
        if(data)
        {
          $.each(data, function(key, value){
           createTagsDropdown(tags_dropdown_incrementor, value);
          });
          createTagsDropdown(tags_dropdown_incrementor);
        }
        else
        {
          createTagsDropdown(tags_dropdown_incrementor);
        }
      }
    );
    if(!this.task_priority_dropdown[line_id])
    {
      $.getJSON("ajax.php?action=getTaskPriority&task_id=" + line_id,
        function(data){
          if(data)
          {
            $("#priority_dropdown").val(data);
          }
        }
      );
    }
    $.ajax({
      url:"ajax.php?action=getTaskNote&task_id=" + line_id,
      success: function(data)
      {
        $("#task_note").val(data);
      }
    });  
    showPage(document.getElementById("tasks"));
    $('#name')
   // .attr('value', decodeURIComponent(event.target.innerHTML))    // modified for task 2831 (due to '%' in name) 
    .attr('value', event.target.innerHTML)
    .attr('name', line_id);
    clear_name_label();
  }
  
  addBSItem = function()
  {
    $.ajax({
      url:"ajax.php?action=addBSItem",
      success: function(data)
      {
        populateBS();
      }
    });
  }
  
  addCounter = function()
  {
    $.ajax({
      url:"ajax.php?action=addCounter",
      success: function(data)
      {
        populateCounters();
      }
    });
  }
  
  populateCounters = function() 
  {
    $.ajax({
      url:"ajax.php?action=populateCounters",
      success: function(lines)
      {
        $("#counters_table").html(lines);
        eipCounters();
        showButtons(['reset_counters', 'add_counter_item']);
      }
    });
  }
  
  showButtons = function(buttons)
  {
    $('.action_bar_item').hide();
    $('#action_bar').show();
    $.each(buttons, function(){
      $('#' + this).show();
    });
  }
  
  clear_name_label = function()
  {
    $("#name_label").html("");
    $("#name").css('margin-left','6px');
  }
     
  listTasks = function(filter, complete, timeframe, sort_field, sort_direction)
  {
    //reset();
    createFilterTagsDropdown();
    if(filter == null) filter = $("#filter_tasks_dropdown").val() ? $("#filter_tasks_dropdown").val() : '';
    filter_val = filter;  
    if(complete == null) complete = $("#filter_tasks_completion_dropdown").val();
    if(timeframe == null) timeframe = $("#filter_tasks_data_span").val();
    if(sort_field == null) sort_field = $("#filter_tasks_sort_field").val();
    if(sort_direction == null) sort_direction = $("#filter_tasks_sort_direction").val();
    $("#filter_tasks_dropdown").val(filter_val);
    filter_name = $("#filter_tasks_dropdown :selected").text();
    $.ajax({
      url:"ajax.php?action=listTasks&filter=" + filter + "&filter_name="  + filter_name + "&complete="  + complete + "&timeframe="  + timeframe + "&sort_field="  + sort_field + "&sort_direction="  + sort_direction,
      success: function(lines)
      {
        if(lines != 'error')
        {
          $("#task_list").html(lines);   
          showButtons(['filter', 'edit_tag_button']);
          //showPage(document.getElementById('task_list'));    
        }
        else
        {
          showMessage('Error listing lines', false);
        }
      }
    });
  }         
  
  listJobs = function()
  {
   $.ajax({
      url:"ajax.php?action=listJobs",
      success: function(lines)
      {
        if(lines != 'error')
        {
          $("#job_log").html(lines);
        }
        else
        {
          showMessage('Error listing lines', false);
        }
      }
    });
  }                 
  
  showMessage = function(message, successful, fadeout, details)
  {
    $(".message").hide();
    if(successful)
    {
      css_class = 'successful';
    }
    else
    {
      css_class = 'failure';
    }
    $(".message").removeClass('successful').removeClass('failure');
    if(typeof(details) != "undefined")
    {
      link = '<a class="message_details_link" href="#">details</a>';
      output = '<div class="message_details" style="font-size:14px; margin:0 200px;">' + details + '</div>';
      $(".message").html(message + link + output).addClass(css_class).fadeIn(1000);
    }
    else
    {
      $(".message").html(message).addClass(css_class).fadeIn(1000);
    }    
    if(fadeout == true){
      $(".message").fadeOut(1000);
    }
  }
  
  saveTask = function()
  {
    if($('#name').val() == '' )
    {
      showMessage('Please enter a value for the name', false);
      setVals();
    } 
    else 
    {
      values = [];
      jQuery.each($('.tags_dropdown'), function(i, val) { 
        if($("#" + val.id).val())values.push($("#" + val.id).val());
      });
      if(values.length == 0)
      {
        showMessage('Please enter at least one tag', false);
      }
      else
      {
        too_long = false;
        strings_array = $('#name').val().split(/\s/);
        for(i = 0; i < strings_array.length; i++){
          if(strings_array[i].length > 27) {
            too_long = true;
          }
        }
        if(too_long){
            showMessage('A word exceeds the max number of characters', false);
        }
        else {
          if($('#name').val().length > max_name_length) {
            excess = $('#name').val().length - max_name_length;
            showMessage('The name exceeds the max number of characters by ' + excess, false)
          }
          else {
            if($('#task_note').val().length > max_note_length) {
              excess = $('#task_note').val().length - max_note_length;
              showMessage('The note exceeds the max number of characters by ' + excess, false)
            }
            else {
              $.ajax({
                url:"ajax.php?action=saveTask&name=" + encodeURIComponent($('#name').val()) + "&id=" + $('#name').attr('name') + "&task_tags=" + encodeURIComponent(values.join(",")) + "&priority=" + $('#priority_dropdown').val() + '&note=' + encodeURIComponent($('#task_note').val()),
                success: function(msg)
                {
                  //listTasks(filter_val);
                  refreshTaskButtons(msg);
                  if($('#name').attr('name'))
                  {
                    showMessage('Successfully updated', true);
                  }
                  else
                  {
                    $('#name').attr('name', msg.replace('Successful',''));
                    showMessage('Successfully added', true);
                  }
                }
              });
            }
          }
        }
      }
    }
  }
  
  remove = function()
  {
  	if(confirm("Really remove this?")){
    	$.ajax({
        url:"ajax.php?action=removeTask&id=" + $('#name').attr('name'),
        success: function(msg)
        {
          if(msg == 'Successful')
          {
            showMessage('Successfully removed', true);
        //    listTasks(filter_val);
          }
          else
          {
            showMessage('Data was NOT saved', false, false, msg);
          }
        }
      });
  	}
  }
  
  
  activate = function()
  {
  	if(confirm("Activate this task?")){
  	  id = $('#name').attr('name');
    	$.ajax({
        url:"ajax.php?action=activateTask&id=" + id,
        success: function(msg)
        {
          if(msg == 'Successful')
          {
            refreshTaskButtons(id);
            showMessage('Successfully activated', true);
        //    listTasks(filter_val);
          }
          else
          {
            showMessage('Task was NOT activated', false, false, msg);
          }
        }
      });
  	}
  }
  
  deactivate = function()
  {
  	if(confirm("Deactivate this task?")){
  	  id = $('#name').attr('name');
    	$.ajax({
        url:"ajax.php?action=deactivateTask&id=" + id,
        success: function(msg)
        {
          if(msg == 'Successful')
          {
            refreshTaskButtons(id);
            showMessage('Successfully deactivated', true);
        //    listTasks(filter_val);
          }
          else
          {
            showMessage('Task was NOT deactivated', false, false, msg);
          }
        }
      });
  	}
  }
  
  completed = function()
  {
  	if(confirm("Has this task been completed?")){
    	$.ajax({
        url:"ajax.php?action=completeTask&id=" + $('#name').attr('name'),
        success: function(msg)
        {
          if(msg == 'Successful')
          {
            showMessage('This task has been marked "Completed"', true);
            $('#not_completed').show(); 
            $('#completed').hide();
          //  listTasks(filter_val);
          }
          else
          {
            showMessage('Data was NOT saved', false, false, msg);
          }
        }
      });
  	}
  }
  
  notCompleted = function()
  {
  	if(confirm("Mark this task *not* completed?")){
    	$.ajax({
        url:"ajax.php?action=notCompleteTask&id=" + $('#name').attr('name'),
        success: function(msg)
        {
          if(msg == 'Successful')
          {
            showMessage('This task has been marked "Not Completed"', true);
            $('#completed').show(); 
            $('#not_completed').hide();
           // listTasks(filter_val);
          }
          else
          {
            showMessage('Data was NOT saved', false, false, msg);
          }
        }
      });
  	}
  }
  
  setVals = function()
  {
     $("#name_label").html(name_label_display);
     $("#name").attr("value", '');
     $("#tags_input").attr("value", '');
     $("#remove").hide();
     $("#completed").hide();
  }
  
  createTagsDropdown = function(tags_dropdown_incrementor, selected_index)
  {
    $("<select>").attr("id", "tags_dropdown" + tags_dropdown_incrementor). attr("class", "tags_dropdown task_page").appendTo("#tags_dropdown");
    $("<option>").attr("value", "").text("Select tag").appendTo("#tags_dropdown" + tags_dropdown_incrementor);
    if(tags_dropdown_incrementor < 2 || recreate_tag_dropdowns)
    {
      $.getJSON("ajax.php?action=getAllTags",
          function(data){
            globalize(data);
            $.each(data, function(key, value){
              $("<option>").attr("value", value.id).text(value.name).appendTo("#tags_dropdown" + tags_dropdown_incrementor);
            });
            if(typeof(selected_index) != "undefined")
            {
              $("#tags_dropdown" + tags_dropdown_incrementor).val(selected_index);
              createTagsDropdown(++tags_dropdown_incrementor);
            }
          }
      );
    }
    else
    {
      $.each(this.all_tags, function(key, value){
        $("<option>").attr("value", value.id).text(value.name).appendTo("#tags_dropdown" + tags_dropdown_incrementor);
      });
      if(typeof(selected_index) != "undefined")
      {
        $("#tags_dropdown" + tags_dropdown_incrementor).val(selected_index.id);
      }
    }
    $("<option>").attr("value", "new").text("Add new tag").appendTo("#tags_dropdown" + tags_dropdown_incrementor).css('font-style', 'italic');
    this.tags_dropdown_incrementor++;
  }
  
  createPriorityDropdown = function()
  {
    $("<select>").attr("id", "priority_dropdown").attr("class", "task_page").appendTo("#priority");
    $("<option>").attr("value", "").text("Select priority").appendTo("#priority_dropdown");
    $.getJSON("ajax.php?action=getPriorities",
        function(data){
          $.each(data, function(key, value){
            $("<option>").attr("value", value.id).text(value.label).appendTo("#priority_dropdown");
          });
          $('#priority_dropdown').val(2);
        }
    );
  }
  
  globalize = function(variable)
  {
    this.all_tags = variable;
    recreate_tag_dropdowns = false;
    recreate_filter_tag_dropdowns = true;
  }
  
  reset = function()
  {
    setVals();
    $("#name").attr("name","");
    $("#tags_dropdown").html("");
    createTagsDropdown(tags_dropdown_incrementor);
    $("#priority").html("");
    createPriorityDropdown();
    $(".message").hide();
    $("#tags").hide();
    $('#task_note').val('');
    $('#lookup_select').val('');
    setTimeout('$("#name").focus();', 500); 
  }
  
  populateBS = function() 
  {
     $.ajax({
      url:"ajax.php?action=populateBS",
      success: function(lines)
      {
        $("#balance_sheet_table").html(lines);
        eipBsd();
        eipBsa();
      }
    });
  }
  
  addBe = function() 
  {
     $.ajax({
      url:"ajax.php?action=addBe&word=" + $("#be_input").val(),
      success: function(lines)
      {
        populateBe();
      }
    });
  }
  
  populateBe = function() 
  {
    $("#be_input").val('');
    $.ajax({
     url:"ajax.php?action=populateBe",
     success: function(lines)
     {
       $("#be_lines").html(lines); 
     }
    });
  }
  
  hideAddressBar = function() 
  { 
    window.scrollTo(0, 1); 
  }
  
  listTags = function()
  {
    $.ajax({
     url:"ajax.php?action=listTags",
     success: function(lines)
     {
       $("#tags_listing").html(lines);
       showPage(document.getElementById('tags_listing')); 
       showButtons(['add_tag']);    
     }
    });
  }
  
  addSuperTag = function(super_tag_id)
  {
    $.ajax({
      url:"ajax.php?action=addSuperTag&super_tag_id=" + super_tag_id + "&this_tag_id=" + $('#tag_name').attr('name'),
      success: function()
      {
        populateTag($('#tag_name').html(), $('#tag_name').attr('name')); 
      }
    });
  }
  
  addSubTag = function(sub_tag_id)
  {
    $.ajax({
      url:"ajax.php?action=addSubTag&sub_tag_id=" + sub_tag_id + "&this_tag_id=" + $('#tag_name').attr('name'),
      success: function()
      {
        populateTag($('#tag_name').html(), $('#tag_name').attr('name')); 
      }
    });
  }
  
  loadHomeShortcuts = function() {
    $('.home_shortcut').remove();
    $.ajax({
      url:"ajax.php?action=loadHomeShortcuts",
      success: function(data)
      {
        $('#bb').prepend(data);
      }
    });
  }

  toggleHomeShortcut = function(tag_id){
    $.ajax({
      url:"ajax.php?action=toggleHomeShortcut&tag_id=" + tag_id + "&checked=" + $('#home_shortcut_tag_checkbox').attr('checked'),
      success: function(response)
      {
        checkHomeShortcut(tag_id);
        loadHomeShortcuts();
        showMessage(response, true);          
      }
    });
  }
  
})();
